package com.manage.competition.service.impl;

import com.manage.competition.entity.CompetitionScore;
import com.manage.competition.mapper.CompetitionScoreMapper;
import com.manage.competition.repository.CompetitionScoreRepository;
import com.manage.competition.service.ICompetitionScoreService;
import com.manage.competition.util.CurrentUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Create with IDEA
 *
 * @Author: gitee.com/KamisamaXX
 * @Date: Create in 22:24 2019/4/10
 * @Description:
 */
@Service
public class CompetitionScoreServiceImpl implements ICompetitionScoreService {

    @Autowired
    private CompetitionScoreMapper competitionScoreMapper;

    @Autowired
    private CompetitionScoreRepository competitionScoreRepository;

    @Override
    public CompetitionScore findByQuestionIdAndUserIdAndTeacherId(Long questionId, Long userId, Long teacherId) {
        return competitionScoreRepository.findByTeacherIdAndUserIdAndQuestionsId(teacherId,userId,questionId);
    }

    @Override
    public int update(CompetitionScore competitionScore) {
        return competitionScoreMapper.updateByPrimaryKeySelective(competitionScore);
    }

    @Override
    public int insert(CompetitionScore competitionScore) {
        competitionScore.setCreateUser(CurrentUserUtil.getCurrentUser().getUsername());
        competitionScore.setUpdateUser(CurrentUserUtil.getCurrentUser().getUsername());
        return competitionScoreMapper.insert(competitionScore);
    }

    @Override
    public int countScore(Long id, List<String> teachers, Long competitionId) {
        int Score = 0;
        for (String teacherId: teachers){
            List<CompetitionScore> scores = competitionScoreRepository.findByUserIdAndTeacherIdAndCompetitionId(id,Long.parseLong(teacherId),competitionId);
            for (CompetitionScore score : scores){
                Score += score.getScore();
            }
        }
        return Score/teachers.size();
    }

    @Override
    public int score(Long teacherId, Long userId, Long competitionId) {
        List<CompetitionScore> list = competitionScoreRepository.findByUserIdAndTeacherIdAndCompetitionId(userId,teacherId,competitionId);
        int result = 0;
        for (CompetitionScore score:list){
            result += score.getScore();
        }
        return result;
    }

    @Override
    public List<CompetitionScore> findByUserIdAndCompetitionId(Long userId, Long competitionId, Long questionId) {
        return competitionScoreRepository.findByUserIdAndCompetitionIdAndQuestionsId(userId,competitionId,questionId);
    }


}
